const OpenAI = require('openai');
const { sendRes } = require('./utils/responseUtils');
const openai = new OpenAI({
  baseURL: 'https://api.deepseek.com',
  apiKey: 'sk-cd695772e0134ba4985801c1fe10cdbf',
});
const dsRole = 'user'; // 还有system
const dsModel = 'deepseek-chat'; // 还有deepseek-reasoner
const rootPath = '/api/ai';
const { AiKeywords } = require('../db');
// AI controller
module.exports = {
  aiController(app) {
    // 优化K语言
    app.post(`${ rootPath }/optimizeKLang`, async (req, res) => {
      try {
        const body = req.body;
        console.log('🚀 ~ body', body);
        const { content } = body;
        if (content?.length > 500) {
          throw new Error('不能超过500字');
        }
        const aiKWRes = (await AiKeywords.findAll({
          where: {
            type: 'optimizeKLang',
          },
        }))?.map(_ => _.dataValues)?.[0] || {};
        // console.log('🚀 ~ aiKWRes', aiKWRes);
        const completion = await openai.chat.completions.create({
          messages: [{
            role: dsRole,
            content: `${ content }

${ aiKWRes.keywords }`,
          }],
          model: dsModel,
        });
        const rlt = completion.choices[0].message.content;
        console.log('🚀 ~ rlt', rlt);
        sendRes(res, { data: rlt });
      } catch (e) {
        console.error('❌ ~ 优化K语言失败', e);
        sendRes(res, { code: -1, msg: e.message });
      }
    });
    // 生成卡效dsModel
    app.post(`${ rootPath }/genCardEffects`, async (req, res) => {
      try {
        const body = req.body;
        console.log('🚀 ~ body', body);
        const { content } = body;
        if (content?.length > 100) {
          throw new Error('不能超过100字');
        }
        const aiKWRes = (await AiKeywords.findAll({
          where: {
            type: 'genCardEffects',
          },
        }))?.map(_ => _.dataValues)?.[0] || {};
        const completion = await openai.chat.completions.create({
          messages: [{
            role: dsRole,
            content: `${ content }

${ aiKWRes.keywords }`,
          }],
          model: dsModel,
        });
        const rlt = completion.choices[0].message.content;
        console.log('🚀 ~ rlt', rlt);
        sendRes(res, { data: rlt });
      } catch (e) {
        console.error('❌ ~ 生成卡效失败', e);
        sendRes(res, { code: -1, msg: e.message });
      }
    });
  },
};
